<template>
  <div class="page-home">
    <TopCalendar
      @handleCurrentDateChange="handleCurrentDateChange"
      @handleAddPlace="handleAddPlace"
    />
    <div class="page-content">
      <Spin v-if="pageLoading" />
      <HomeContent
        v-else
        :dataSource="dataSource"
        :venueInfo="venueInfo"
        @handleAddPlace="handleAddPlace"
        @handleCancelReservation="handleCancelReservation"
      />
    </div>
  </div>
  <CreateModal
    v-model:createModel="createModel"
    :venueInfo="venueInfo"
    :currentDate="currentDate"
    :createVenue="createVenue"
    :createTime="createTime"
    @createSuccess="getList"
  />
  <CancelModal
    v-model:cancelModel="cancelModel"
    :venueInfo="venueInfo"
    :currentDate="currentDate"
    :cancelVenue="createVenue"
    :cancelTime="createTime"
    @cancelSuccess="getList"
  />
</template>
<script setup lang="ts" name="Home">
import { getVenueList, getVenueReservationByDate } from '@/api/reserve-home/index'
import TopCalendar from './top-calendar/index.vue'
import HomeContent from './home-content/index.vue'
import CreateModal from './create-modal/index.vue'
import CancelModal from './cancel-modal/index.vue'
import { onMounted, ref, type Ref } from 'vue'
import type { VenueInfo, VenueReservationItem } from '#/reserve-home'
import dayjs from 'dayjs'

const venueInfo: Ref<VenueInfo> = ref({
  venueNumber: 0,
  startTime: '09:00',
  endTime: '22:00'
})

const pageLoading = ref(false)
const dataSource: Ref<VenueReservationItem[]> = ref([])
const currentDate = ref('')
const handleCurrentDateChange = (date: string) => {
  currentDate.value = date
  getList()
}

const getList = () => {
  pageLoading.value = true
  getVenueReservationByDate(currentDate.value)
    .then((res: { data: VenueReservationItem[] }) => {
      dataSource.value = res.data
      pageLoading.value = false
    })
    .catch(() => {
      pageLoading.value = false
    })
}

const createModel = ref(false)
const createVenue: Ref<number[]> = ref([])
const createTime = ref('')
const handleAddPlace = (venue: number[] = [], time = '') => {
  createVenue.value = venue
  createTime.value = time
  createModel.value = true
}

const cancelModel = ref(false)
const handleCancelReservation = (venue: number[] = [], time = '') => {
  createVenue.value = venue
  createTime.value = time
  cancelModel.value = true
}

const getDefault = () => {
  getVenueList().then(
    (res: { data: { venueNumber: number; startTime: string; endTime: string } }) => {
      if (res.data) {
        venueInfo.value.venueNumber = res.data.venueNumber
        venueInfo.value.startTime = res.data.startTime
        venueInfo.value.endTime = res.data.endTime
        handleCurrentDateChange(dayjs().format('YYYY-MM-DD'))
      }
    }
  )
}

onMounted(() => {
  getDefault()
})
</script>
<style lang="less" scoped></style>
